package com.ddsso.auth.web.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ddsso.auth.web.session.SessionUserEntity;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zdd
 * @package com.ddsso.auth.web.util
 * @Time Created by zdd on 2016/11/11.
 * @description To-do
 */
public class RequestUtil {
    /**
     * 得到当前线程运行的HttpRequest对象
     * @return
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return  servletRequestAttributes.getRequest();
    }

    /**
     * 获取当前用户
     * @return
     */
    public static SessionUserEntity getCurrentUser(){
        /**
         * @description 修改当前Session的获取方式，通过Shiro中session失效控制，来控制是否是分布式session
         * @author zdd
         */
        Session session= SecurityUtils.getSubject().getSession();
        if(session==null){
            HttpServletRequest req = getRequest();
            session = (Session) req.getSession();
        }
        SessionUserEntity user  =(SessionUserEntity) session.getAttribute(SessionUserEntity.SESSION_USER_KEY);
        return user;
    }

    /**
     * 添加会话级变量
     * @param key
     * @param value
     */
    public static void setSessionAttribute(String key,Object value){
        getRequest().getSession().setAttribute(key, value);
    }

    /**
     * 从该会话中，取得变量信息
     * @param key
     */
    public static Object getSessionAttribute(String key){
        return getRequest().getSession().getAttribute(key);
    }

    /**
     * 删除变量信息
     * @param key
     */
    public static void removeSessionAttribute(String key) {
	getRequest().getSession().removeAttribute(key);
    }

    /**
     * 获取IP
     * @return
     */
    public static String ip_address() {
        HttpServletRequest request = getRequest();
        if (null == request) {
            return "";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.indexOf(",") != -1) { //只取第一个IP地址
            ip = ip.substring(0, ip.indexOf(","));
        }
        return ip;
    }
}
